<template>
	<view class="page-container">
		<view class="info-container">
			<view class="info-item-container">
				<view calss="info-item-label">
					原手机号
				</view>
				<view class="info-item-value-container">
					<input type="number" maxlength="11" v-model='formData.mobile' disabled="true" placeholder="请输入手机号"
						confirm-type="done">
				</view>
			</view>
			<view class="info-item-container">
				<view calss="info-item-label">
					验证码
				</view>
				<view class="info-item-value-container">
					<input type="number" maxlength="6" placeholder="请输入验证码" v-model='formData.captcha' confirm-type="done">
					<text v-if="countdownTime == COUNTDOWN_DURATION" @click='getVerificationCode'
						class="send-verification">发送验证码</text>
					<text v-else @click='getVerificationCode'> {{Math.ceil(countdownTime/1000)}} s</text>
				</view>
			</view>
			<view class="info-item-container">
				<view calss="info-item-label">
					修改手机号
				</view>
				<view class="info-item-value-container">
					<input type="number" maxlength="11" v-model='formData.new_mobile' placeholder="请输入手机号"
						confirm-type="done">
				</view>
			</view>
		</view>
		<view class="save-mobile" @click="saveChange">
			保存
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, shallowRef, reactive } from "vue";
	import { onShow, onHide } from '@dcloudio/uni-app';
	import { useShowToast } from "@/utils/tools";
	import { sendSmsVerificationCode } from "@/api/public";
	import { apiChangeMobile } from "../../api/user";


	const formData = reactive({
		mobile: "",
		captcha: "",
		new_mobile: "",
	})

	/*------------------------------------------------ 验证码相关 ------------------------------------------------*/
	const VERIFICATION_CODE_CACHE_TIMESTAMP_KEY = shallowRef<string>("verificationCodeEndTimestampPhoto");
	const COUNTDOWN_DURATION = 60000; 	// 倒计时总时间（毫秒秒）
	let countdownTime = ref<number>(COUNTDOWN_DURATION);
	let countdownRuning = ref<boolean>(false);
	/**
	 * 获取短信验证码，缓存一个时间戳，保证用户不会利用多次进退来刷新次数，以及继续上一次的倒计时
	 */
	const getVerificationCode = async () => {
		if (!checkMobile) return
		try {
			// 发送短信验证码请求
			const response = await sendSmsVerificationCode(formData.mobile, 'mobilelogin');
			useShowToast(response.msg);
			// 计算验证码有效截止时间，并将其存储到本地缓存
			const entTime = Date.now() + COUNTDOWN_DURATION;
			uni.setStorageSync(VERIFICATION_CODE_CACHE_TIMESTAMP_KEY.value, String(entTime));
			// 开始倒计时
			countDown(entTime);
		} catch (err) {
			console.error(err);
		}
	}

	/**
	 * 倒计时算法
	 */
	const countDown = (targetTimestamp : number) => {
		if (countdownRuning.value) return
		countdownRuning.value = true;
		const tick = () => {
			setTimeout(() => {
				const remainingTime = targetTimestamp - Date.now()
				if (remainingTime >= 0) {
					countdownTime.value = remainingTime
					tick()
				} else {
					countdownRuning.value = false
					uni.removeStorageSync(VERIFICATION_CODE_CACHE_TIMESTAMP_KEY.value);
					countdownTime.value = COUNTDOWN_DURATION
				}
			}, 100)
		}
		tick()
	}

	/**
	 * 检测是否需要继续的倒计时
	 */
	const checkCountDown = () => {
		console.log('检测是否继续', VERIFICATION_CODE_CACHE_TIMESTAMP_KEY.value)
		const SOTRE_TIMESTAMP = uni.getStorageSync(VERIFICATION_CODE_CACHE_TIMESTAMP_KEY.value);
		if (Date.now() < parseInt(SOTRE_TIMESTAMP)) {
			console.log("旧的时间戳还没过期需要继续执行")
			countDown(parseInt(SOTRE_TIMESTAMP))
		} else {
			uni.removeStorageSync(VERIFICATION_CODE_CACHE_TIMESTAMP_KEY.value);
		}
	}

	/**
	 * 保存修改
	 */
	const saveChange = async () => {
		if (!checkMobile(formData.mobile)) return
		if (formData.captcha.length === 0) {
			useShowToast("验证码不能为空");
			return;
		} else if (formData.captcha.length < 6) {
			useShowToast("验证码错误");
			return;
		}
		if (!checkNewMobile(formData.new_mobile)) return
		try {
			uni.showLoading({
				mask:true
			})
			await apiChangeMobile(formData);
			const storageInfo = uni.getStorageSync('userInfo');
			storageInfo.mobile = formData.new_mobile;
			uni.setStorageSync('userInfo', storageInfo);
			uni.hideLoading();
			useShowToast('修改成功', "success", true);
			setTimeout(() => {
				uni.navigateBack()
			}, 2000)
		} catch (err) {
			uni.hideLoading()
			useShowToast('保存失败,请稍后再试')
		}

	}

	/**
	 * 检查原手机号
	 */
	const checkMobile = (phoneNumber : string) => {
		const phoneNumberRegex = /^(?:1(?:[1-9]\d|\d[3-9])\d{8})$/;
		// 根据手机号合法性显示相应提示并返回检查结果
		if (phoneNumber === '') {
			useShowToast("原手机号不能为空");
			return false;
		}
		if (!phoneNumberRegex.test(phoneNumber)) {
			useShowToast("请输入正确的手机号");
			return false;
		}
		return true;
	}

	/**
	 * 检查新手机号
	 */
	const checkNewMobile = (phoneNumber : string) => {
		const phoneNumberRegex = /^(?:1(?:[1-9]\d|\d[3-9])\d{8})$/;
		// 根据手机号合法性显示相应提示并返回检查结果
		if (phoneNumber === '') {
			useShowToast("新手机号不能为空");
			return false;
		}
		if (!phoneNumberRegex.test(phoneNumber)) {
			useShowToast("请输入正确的新手机号");
			return false;
		}
		return true;
	}


	onShow(() => {
		checkCountDown();
		const storageInfo = uni.getStorageSync("userInfo");
		formData.mobile = storageInfo.mobile;
	})


	onHide(() => {
		console.log('页面停止')
	})
</script>

<style lang="scss" scope>
	.page-container {
		.info-container {
			padding: 52rpx 60rpx 0 60rpx;

			.info-item-container {
				padding-top: 42rpx;

				.info-item-label {
					font-size: 28rpx;
					color: #FFFFFF;
					line-height: 28rpx;
				}

				.info-item-value-container {
					display: flex;
					align-items: center;
					justify-content: space-between;
					height: 94rpx;
					border-bottom: 1rpx solid #4A4A4A;

					.send-verification {
						color: #25DADA;
					}
				}
			}
		}

		.save-mobile {
			text-align: center;
			width: 630rpx;
			height: 80rpx;
			background-color: #25DADA;
			border-radius: 80rpx;
			margin: 0 auto;
			margin-top: 100rpx;
			line-height: 80rpx;
			color: $uni-text-color;
		}
	}
</style>